package com.dhcc.DRGsHosp.web.controller;

import com.dhcc.DRGsHosp.facade.DictionaryDataFacade;
import com.dhcc.DRGsHosp.facade.FieldMapFacade;
import com.dhcc.DRGsHosp.facade.InitializeFacade;
import com.dhcc.DRGsHosp.infra.util.GlobalData;
import org.codehaus.jackson.map.ObjectMapper;
import org.openkoala.koala.commons.InvokeResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * 
 * @title		:XmlStructureController.java
 * @description	:xml结构
 * @author		:mazhaoyan
 * @date		:2017年4月18日
 * @version     :1.0
 * @copyright   :DHCC 2013-2014
 */


@Controller("drgsHospWebControllerMzy180122")
@RequestMapping(value="fieldMap")
public class FieldMapController {
	@Autowired
	private FieldMapFacade fieldMapFacade;
	@Autowired
	private DictionaryDataFacade dictionaryDataFacade;
	@Autowired
	private InitializeFacade initializeFacade;
	
	private String filePath = "";
	@ResponseBody
	@RequestMapping("/filesUpload")  
    public InvokeResult filesUpload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {  
		String fileCat = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//定义一个随时间变化的变量，加在filename前，使上传的文件不重复
		//创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){  
                //记录上传过程起始时的时间，用来计算上传时间  
                int pre = (int) System.currentTimeMillis();  
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){  
                    //取得当前上传文件的文件名称  
                    String myFileName = file.getOriginalFilename();  
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                    if(myFileName.trim() !=""){

                        System.out.println(myFileName);  
                        //重命名上传后的文件名  
                        String fileName = fileCat+"_"+ file.getOriginalFilename();  
                        //定义上传路径  
                        String path = request.getSession().getServletContext().getRealPath("/")+"upload";
                        File localFile = new File(path);
                        if (!localFile.exists()) {
							localFile.mkdirs();
						}
                        localFile = new File(path + File.separatorChar + fileName);
                        try {
							file.transferTo(localFile);
							filePath = path + File.separatorChar + fileName;
						} catch (Exception e) {
							e.printStackTrace();
						}//文件上传至服务器  
                    }  
                }  
                //记录上传该文件后的时间  
                int finaltime = (int) System.currentTimeMillis();  
                System.out.println("本文件上传时间："+(finaltime - pre)+"ms");  
            }  
        }  
        return InvokeResult.success(filePath);
    } 
	/**
	 * 
	 *  readJson.  
	 *  @Description：解析字段映射数据
	 *  @Author mazhaoyan
	 *  @return 
	 *  @Date:2018年1月22日下午8:58:09
	 */
	@ResponseBody
	@RequestMapping("/parseData")
	public InvokeResult parseData( String fileType, String repeatNode){
		InvokeResult invokeResult = fieldMapFacade.parseData(filePath,fileType,repeatNode);
		//更新系统配置全局变量
		initializeFacade.initializeSysConfig();
		return invokeResult;
		
	}
	/**
	 * 
	 *  getTableData.  
	 *  @Description：获取表格数据
	 *  @Author mazhaoyan
	 *  @return 
	 *  @Date:2018年1月22日下午10:19:23
	 */
	@ResponseBody
	@RequestMapping("/getTableData")
	public InvokeResult getTableData(@RequestParam String fileType){
		return fieldMapFacade.getTableData(fileType);
	}
	/**
	 * 
	 *  getFileTypes.  
	 *  @Description：获取系统已经配置的首页文件类型字典
	 *  @Author mazhaoyan
	 *  @return 
	 *  @Date:2018年1月23日下午5:11:53
	 */
	@ResponseBody
	@RequestMapping("/getFileTypes")
	public InvokeResult getFileTypes(){
		return dictionaryDataFacade.findDictionaryDataByCode("MR_FILE_TYPE");
	}
	/**
	 * 
	 *  getConfigFileType.  
	 *  @Description：文件上传时 首页文件类型 选定的文件字段映射关系
	 *  @Author mazhaoyan
	 *  @return 
	 *  @Date:2018年1月23日下午5:13:01
	 */
	@ResponseBody
	@RequestMapping("/getConfigFileType")
	public InvokeResult getConfigFileType(){
		return InvokeResult.success(GlobalData.sysConfig.get("MR_FILE_TYPE"));
	}
	
	/**
	 * 
	 *  saveSingleField.  
	 *  @Description：保存单个映射信息
	 *  @Author mazhaoyan
	 *  @param mapInfo
	 *  @return 
	 *  @Date:2018年1月23日下午10:27:51
	 */
	@ResponseBody
	@RequestMapping("/saveSingleField")
	public InvokeResult saveSingleField(@RequestParam String mapInfo){
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> entity;
		try {
			entity = objectMapper.readValue(mapInfo, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
			entity = new HashMap<String, Object>();
		}
		InvokeResult invokeResult = fieldMapFacade.saveSingleField(entity);
		//更新系统配置全局变量
		initializeFacade.initializeSysConfig();
		return invokeResult;
	}
	/**
	 *  @Discription：删除映射关系
	 *  @Author： liuhongjun
	 *  @param mapInfo
	 *  @return
	 *  @Date:2018年5月7日下午3:15:05
	 */
	@ResponseBody
	@RequestMapping("/deleteFieldMap")
	public InvokeResult deleteFieldMap(@RequestParam String mapInfo){
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> entity;
		try {
			entity = objectMapper.readValue(mapInfo, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
			entity = new HashMap<String, Object>();
		}
		return fieldMapFacade.deleteFieldMap(entity);
	}
	
	
}
